package com.gwsdk.paysdk.acitvityV2;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.gwsdk.open.ApiCallback;
import com.gwsdk.open.FlagControl;
import com.gwsdk.paysdk.acitvityV2.adapter.GWCouponAdapter;
import com.gwsdk.paysdk.activity.GWWapPayActivity;
import com.gwsdk.paysdk.bean.CouponBean;
import com.gwsdk.paysdk.bean.GWPayModel;
import com.gwsdk.paysdk.bean.PersonalCenterModel;
import com.gwsdk.paysdk.bean.UserReLogin;
import com.gwsdk.paysdk.bean.pay.ZfbPay;
import com.gwsdk.paysdk.callback.WFTWapPayCallback;
import com.gwsdk.paysdk.callback.ZFBWapPayCallback;
import com.gwsdk.paysdk.common.Constant;
import com.gwsdk.paysdk.dialog.GWTipDialog;
import com.gwsdk.paysdk.dialog.PTBPayResultDialog;
import com.gwsdk.paysdk.entity.GamePayTypeEntity;
import com.gwsdk.paysdk.entity.PTBPayResult;
import com.gwsdk.paysdk.entity.UserDiscountEntity;
import com.gwsdk.paysdk.entity.UserPTBInfo;
import com.gwsdk.paysdk.entity.WXOrderInfo;
import com.gwsdk.paysdk.http.process.CouponUseableProcess;
import com.gwsdk.paysdk.http.process.PTBPayProcess;
import com.gwsdk.paysdk.http.process.PayTypeProcess;
import com.gwsdk.paysdk.http.process.UserDiscountProcess;
import com.gwsdk.paysdk.http.process.UserPtbBalanceProcess;
import com.gwsdk.paysdk.http.process.UserPtbRemainProcess;
import com.gwsdk.paysdk.http.process.WFTOrderInfoProcess;
import com.gwsdk.paysdk.listener.OnMultiClickListener;
import com.gwsdk.paysdk.utils.GWInflaterUtils;
import com.gwsdk.paysdk.utils.GWLog;
import com.gwsdk.paysdk.utils.GWMoneyUtils;
import com.gwsdk.paysdk.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class GWPayActivity extends GWBaseActivity implements View.OnClickListener {

    private String TAG = "GWPayActivity";

    private View selectCouponBtn;
    private View selectPayBtn;
    private View payView;
    private View couponView;
    private View couponBack;
    private View payTypeView;
    private View payBack;

    private View alipayItemView;
    private View platformCoinItemView;
    private View balanceItemView;
    private View wechatItemView;

    private ListView listView;
    private TextView coinTV;
    private TextView balanceTV;
    private ImageView alipayImage;
    private ImageView platformCoinImage;
    private ImageView balanceImage;
    private ImageView wechatImage;

    private ImageView selectPayIcon;
    private TextView selectPayText;
    private TextView orderPriceTV;
    private float buyGoodsDiscount;

    private boolean isHaveDiscount;

    private boolean isBind; //选中的是平台币还是绑币支付
    private String couponID = ""; //选中的代金券id
    private String price; //原价
    private String realPrice;  //最终的实际价格

    private double couponPrice; //减去代金券后的价格

    // 用户平台币余额
    private String userPtbMoney = "";
    // 用户绑定平台币余额
    private String userBindPtbMoney = "";

    private boolean isZFBWapPay; //用于操作支付宝支付时是走App支付还是WAP支付
    private TextView tvGWPrice;
    private TextView orderName;
    private TextView couponCountTV;

    private View closeBtn;
    private GWCouponAdapter adapter;
    private List<CouponBean> couponList = new ArrayList<>(); //满足金额条件，可用的代金券
    private CouponBean currentCoupon;
    GamePayTypeEntity typeEntity;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        this.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏 
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//去掉信息栏(主要功能就是去除页面弹出时顶部黑色条)

        ComeOutType();
        super.onCreate(savedInstanceState);
        Configuration mConfiguration = this.getResources().getConfiguration(); //获取设置的配置信息
        int ori = mConfiguration.orientation; //获取屏幕方向
        setContentView(GWInflaterUtils.getLayout(this,"gw_activity_pay"));

        price = ApiCallback.order().getGoodsPriceYuan();
        realPrice = price;
        couponPrice = Double.parseDouble(price);

        initView();

        initCoupon();
        initPay();
    }


    private void initView(){

        alipayItemView = findViewById(GWInflaterUtils.getControl(this,"alipay_item"));
        platformCoinItemView = findViewById(GWInflaterUtils.getControl(this,"platform_coin_item"));
        balanceItemView = findViewById(GWInflaterUtils.getControl(this,"balance_item"));
        wechatItemView = findViewById(GWInflaterUtils.getControl(this,"wechat_item"));

        alipayImage = findViewById(GWInflaterUtils.getControl(this,"alipay_item_selected"));
        platformCoinImage = findViewById(GWInflaterUtils.getControl(this,"platform_coin_item_selected"));
        balanceImage = findViewById(GWInflaterUtils.getControl(this,"balance_img_selected"));
        wechatImage = findViewById(GWInflaterUtils.getControl(this,"wechat_item_select"));

        listView = findViewById(GWInflaterUtils.getControl(this,"list_view"));

        selectPayIcon = findViewById(GWInflaterUtils.getControl(this,"select_pay_type_icon"));
        selectPayText = findViewById(GWInflaterUtils.getControl(this,"select_pay_type_tv"));

        orderPriceTV = findViewById(GWInflaterUtils.getControl(this,"order_price_tv"));
        orderName = findViewById(GWInflaterUtils.getControl(this,"order_name"));
        couponCountTV = findViewById(GWInflaterUtils.getControl(this,"coupon_count_tv"));

        coinTV = findViewById(GWInflaterUtils.getControl(this,"coin_tv"));
        balanceTV = findViewById(GWInflaterUtils.getControl(this,"balance_tv"));
        tvGWPrice = findViewById(GWInflaterUtils.getControl(this,"gw_price_tv"));

        selectCouponBtn = findViewById(GWInflaterUtils.getControl(this,"select_coupon_button"));
        selectPayBtn = findViewById(GWInflaterUtils.getControl(this,"select_pay_type"));

        payView = findViewById(GWInflaterUtils.getControl(this,"pay_view"));
        payTypeView = findViewById(GWInflaterUtils.getControl(this,"pay_type_view"));
        couponView = findViewById(GWInflaterUtils.getControl(this,"coupon_view"));

        payBack = findViewById(GWInflaterUtils.getControl(this,"pay_back"));
        couponBack = findViewById(GWInflaterUtils.getControl(this,"coupon_back"));

        closeBtn = findViewById(GWInflaterUtils.getControl(this,"close_btn"));

        alipayItemView.setOnClickListener(this);
        platformCoinItemView.setOnClickListener(this);
        balanceItemView.setOnClickListener(this);
        wechatItemView.setOnClickListener(this);
        View pay_btn = findViewById(GWInflaterUtils.getControl(this,"pay_btn"));
        pay_btn.setOnClickListener(startPayListener);

        closeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });



        adapter = new GWCouponAdapter(this,handler,true);


        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                couponList.get(position).setSelected(true);
                currentCoupon = couponList.get(position);
                couponID = currentCoupon.getId();
                couponCountTV.setText("满"+currentCoupon.getLimit_money() + "元减"+currentCoupon.getMoney() + "元");
                adapter.notifyDataSetChanged();
                payView.setVisibility(View.VISIBLE);
                couponView.setVisibility(View.GONE);
                setPrice();
            }
        });


        selectCouponBtn.setOnClickListener(this);
        selectPayBtn.setOnClickListener(this);
        couponBack.setOnClickListener(this);
        payBack.setOnClickListener(this);



        String productPrice = String.format(Locale.CHINA, "￥%.2f元", Float.parseFloat(price));
        orderPriceTV.setText(productPrice);
        orderName.setText( ApiCallback.order().getProductName());
    }

    private void ComeOutType() {
        Window window = getWindow();
        window.requestFeature(Window.FEATURE_NO_TITLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        window.setDimAmount(0f); //设置背景透明度   0~1
        overridePendingTransition(GWInflaterUtils.getIdByName(this,"anim","gw_scale_in"),0);// R.anim.,0);
    }

    Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Constant.ALL_COUPON_SUCCESS:

                    break;
                case Constant.ALL_COUPON_FAIL:

                    break;
                case Constant.GET_REBATE_SUCCESS:

                    break;

                case Constant.GET_REBATE_FAIL:

                    break;
            }
        }
    };

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(GWInflaterUtils.getIdByName(this,"anim","gw_scale_in"),
                GWInflaterUtils.getIdByName(this,"anim","gw_scale_out"));// R.anim.,0);
    }

    private int payType = 1;  //选中的支付方式：1支付宝 2微信 3余额 4平台币
    @Override
    public void onClick(View v) {
        if (v.getId() == selectCouponBtn.getId()){
            if (couponList.size() <= 0){
                ToastUtil.show("暂无可使用代金券");
            }else {
                payView.setVisibility(View.GONE);
                couponView.setVisibility(View.VISIBLE);
            }
        }else if (v.getId() == GWInflaterUtils.getControl(this,"coupon_back")){
            payView.setVisibility(View.VISIBLE);
            couponView.setVisibility(View.GONE);
        }else if (v.getId() == GWInflaterUtils.getControl(this,"pay_back")){
            payView.setVisibility(View.VISIBLE);
            payTypeView.setVisibility(View.GONE);
        }else if(v.getId() == GWInflaterUtils.getControl(this,"select_pay_type")){
            payView.setVisibility(View.GONE);
            payTypeView.setVisibility(View.VISIBLE);
        }else if(v.getId() == GWInflaterUtils.getControl(this,"alipay_item")){
            isBind = false;
            payType = 1;
            alipayImage.setImageResource(GWInflaterUtils.getDrawable(this,"gw_selected_icon"));
            platformCoinImage.setImageResource(GWInflaterUtils.getDrawable(this,"gw_selected_no_icon"));
            balanceImage.setImageResource(GWInflaterUtils.getDrawable(this,"gw_selected_no_icon"));
            wechatImage.setImageResource(GWInflaterUtils.getDrawable(this,"gw_selected_no_icon"));
            selectPayIcon.setImageResource(GWInflaterUtils.getDrawable(this,"gw_zhifubao_icon"));
            selectPayText.setText("支付宝");
            payView.setVisibility(View.VISIBLE);
            payTypeView.setVisibility(View.GONE);
            setPrice();
        }else if(v.getId() == GWInflaterUtils.getControl(this,"platform_coin_item")){
            isBind = false;
            payType = 4;
            platformCoinImage.setImageResource(GWInflaterUtils.getDrawable(this,"gw_selected_icon"));
            alipayImage.setImageResource(GWInflaterUtils.getDrawable(this,"gw_selected_no_icon"));
            balanceImage.setImageResource(GWInflaterUtils.getDrawable(this,"gw_selected_no_icon"));
            wechatImage.setImageResource(GWInflaterUtils.getDrawable(this,"gw_selected_no_icon"));
            selectPayIcon.setImageResource(GWInflaterUtils.getDrawable(this,"gw_pingtaibi_icon"));
            selectPayText.setText("平台币");
            payView.setVisibility(View.VISIBLE);
            payTypeView.setVisibility(View.GONE);
            setPrice();
        }else if(v.getId() == GWInflaterUtils.getControl(this,"balance_item")){
            isBind = true;
            payType = 3;
            balanceImage.setImageResource(GWInflaterUtils.getDrawable(this,"gw_selected_icon"));
            alipayImage.setImageResource(GWInflaterUtils.getDrawable(this,"gw_selected_no_icon"));
            platformCoinImage.setImageResource(GWInflaterUtils.getDrawable(this,"gw_selected_no_icon"));
            wechatImage.setImageResource(GWInflaterUtils.getDrawable(this,"gw_selected_no_icon"));
            selectPayIcon.setImageResource(GWInflaterUtils.getDrawable(this,"gw_wodeyuer_icon"));
            selectPayText.setText("余额");
            payView.setVisibility(View.VISIBLE);
            payTypeView.setVisibility(View.GONE);
            setPrice();
        }else if(v.getId() == GWInflaterUtils.getControl(this,"wechat_item")){
            isBind = false;
            payType = 2;
            wechatImage.setImageResource(GWInflaterUtils.getDrawable(this,"gw_selected_icon"));
            balanceImage.setImageResource(GWInflaterUtils.getDrawable(this,"gw_selected_no_icon"));
            alipayImage.setImageResource(GWInflaterUtils.getDrawable(this,"gw_selected_no_icon"));
            platformCoinImage.setImageResource(GWInflaterUtils.getDrawable(this,"gw_selected_no_icon"));
            selectPayIcon.setImageResource(GWInflaterUtils.getDrawable(this,"gw_weixin_icon"));
            selectPayText.setText("微信");
            payView.setVisibility(View.VISIBLE);
            payTypeView.setVisibility(View.GONE);
            setPrice();
        }
    }

    private void initPay() {
        buyGoodsDiscount = 10;
        UserDiscountProcess discountProcess = new UserDiscountProcess(); //请求折扣信息
        discountProcess.post(disHandler);

        UserPtbBalanceProcess ptbBalanceProcess = new UserPtbBalanceProcess();//请求平台币、绑币余额信息
        ptbBalanceProcess.post(coinHandler);

        PayTypeProcess payTypeProcess = new PayTypeProcess();  //请求支付方式列表
        payTypeProcess.post(payTypeHandler);
    }

    public void initCoupon() {
        CouponUseableProcess useableProcess = new CouponUseableProcess(); //请求可用满减券
        useableProcess.setPrice(price);
        useableProcess.setBind("0");
        useableProcess.post(couponHandler);
    }

    private final Handler couponHandler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == Constant.USABLE_COUPON_SUCCESS) {
                couponList.clear();
                List<CouponBean> array = (List<CouponBean>) msg.obj;

                if (array != null){
                    couponList.addAll(array);
                    adapter.setData(couponList);
                }
                if (couponList.size() <= 0){
                    couponCountTV.setText("暂无可使用代金券");
                }else {
                    couponCountTV.setText(String.format(Locale.CHINA, "%d张可用", couponList.size()));
                }
            }
            return false;
        }
    });

    //进入支付页面，默认支付宝，没有代金券
    private final Handler disHandler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == Constant.GET_USER_DISCOUNT_SUCCESS) {
                UserDiscountEntity userDiscount = (UserDiscountEntity) msg.obj;
                buyGoodsDiscount = userDiscount.getDiscountNum();  //折扣
                if (0 != userDiscount.getDiscountType() && 10 != userDiscount.getDiscountNum()) {
                    isHaveDiscount = true;
                }
                setPrice();
            }else {
                ToastUtil.show(GWPayActivity.this, (String) msg.obj);
            }
            return false;
        }
    });

    private void setPrice(){
        if (isHaveDiscount){
            if (payType == 4){
                if (currentCoupon != null){
                    float p = Float.parseFloat(price) - Float.parseFloat(currentCoupon.getMoney());
                    if (p < 0){
                        p = 0;
                    }
                    realPrice = String.format(Locale.CHINA, "%.0f", (p * 10) * (buyGoodsDiscount / 10.0));
                }else {
                    realPrice = String.format(Locale.CHINA, "%.0f", (Float.parseFloat(price) * 10) * ( buyGoodsDiscount / 10.0));
                }
                tvGWPrice.setText(String.format("%s（%s折）", realPrice, buyGoodsDiscount));
            }else {
                if (currentCoupon != null){
                    float p = Float.parseFloat(price) - Float.parseFloat(currentCoupon.getMoney());
                    if (p < 0){
                        p = 0;
                    }
                    realPrice = String.format(Locale.CHINA, "%.2f", p * (buyGoodsDiscount / 10));
                }else {
                    realPrice = String.format(Locale.CHINA, "%.2f", Float.parseFloat(price) * (buyGoodsDiscount / 10));
                }
                tvGWPrice.setText(String.format("￥%s元（%s折）", realPrice, buyGoodsDiscount));
            }
        }else {
            if (payType == 4){
                if (currentCoupon != null){
                    float p = Float.parseFloat(price) - Float.parseFloat(currentCoupon.getMoney());
                    if (p < 0){
                        p = 0;
                    }
                    realPrice = String.format(Locale.CHINA, "%.0f", p * 10);
                }else {
                    realPrice = String.format(Locale.CHINA, "%.0f", Float.parseFloat(price) * 10);
                }
                tvGWPrice.setText(String.format("%s", realPrice));
            }else {
                if (currentCoupon != null){
                    float p = Float.parseFloat(price) - Float.parseFloat(currentCoupon.getMoney());
                    if (p < 0){
                        p = 0;
                    }
                    realPrice = String.format(Locale.CHINA, "%.2f", p);
                }else {
                    realPrice = String.format(Locale.CHINA, "%.2f", Float.parseFloat(price));
                }
                tvGWPrice.setText(String.format("￥%s元", realPrice));
            }
        }
    }

    private final Handler coinHandler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == Constant.PTB_BALANCE_SUCCESS) {
                UserPTBInfo userPtb = (UserPTBInfo) msg.obj;
                balanceItemView.setVisibility(View.VISIBLE);
                platformCoinItemView.setVisibility(View.VISIBLE);
                balanceTV.setText(String.format(Locale.CHINA, "(%.0f)", userPtb.getPtbMoney()));
                coinTV.setText(String.format(Locale.CHINA, "(%.0f)", userPtb.getBindptbMoney()));
            }else {
                ToastUtil.show(GWPayActivity.this, (String) msg.obj);
            }
            return false;
        }
    });

    private final Handler payTypeHandler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (Constant.GAME_PAY_TYPE_SUCCESS == msg.what) {
                typeEntity = (GamePayTypeEntity)msg.obj;
                isZFBWapPay = typeEntity.ZFBisWapPay;// || !DeviceInfo.checkAliPayInstalled(GWPayActivity.this);
                boolean isOpenZFB = typeEntity.isHaveZFB;
                boolean isOpenWX = typeEntity.isHaveWX;
                alipayItemView.setVisibility(isOpenZFB ? View.VISIBLE : View.GONE);
                wechatItemView.setVisibility(isOpenWX ? View.VISIBLE : View.GONE);
                balanceItemView.setVisibility(typeEntity.isHavePTB ? View.VISIBLE : View.GONE);
                platformCoinItemView.setVisibility(typeEntity.isHaveBindPtb ? View.VISIBLE : View.GONE);
            }else {
                ToastUtil.show(GWPayActivity.this, (String) msg.obj);
            }
            return false;
        }
    });

    //开始发起支付
    private final View.OnClickListener startPayListener = new OnMultiClickListener() {
        @Override
        public void onMultiClick(View v) {
            String sessionuid = PersonalCenterModel.getInstance().getUserId();
            if (!TextUtils.isEmpty(sessionuid)) {
                startPay();
            } else {
                UserReLogin reLogin = new UserReLogin(GWPayActivity.this);
                reLogin.userToLogin(new UserReLogin.ReLoginCallback() {
                    @Override
                    public void reLoginResult(boolean res) {
                        GWLog.e("GWPayActivity", "reLogin res = " + res);
                        if (res) {
                            startPay();
                        } else {
                            ToastUtil.show(GWPayActivity.this, "请登录");
                        }
                    }
                });
            }
        }
    };

    private void startPay(){
        switch (payType){
            case 1:
                zfbPayProcess();
                break;
            case 2:
                wftPayProcess();
                break;
            case 3:
                queryUserPtbMoney(true);
                break;
            case 4:
                queryUserPtbMoney(false);
                break;
        }
    }
    /**
     * 获取用户平台币余额信息
     * PTBtype: true是平台币 false是绑币
     */
    private void queryUserPtbMoney(boolean PTBtype) {
        if (PTBtype){
            showDialog("获取平台币信息..");
        }else {
            showDialog("获取绑币信息..");
        }
        new UserPtbRemainProcess().post(cpHandler,PTBtype);
    }

    // TODO 微富通 支付请求------------------start
    private void wftPayProcess() {
        showDialog("给微信下单...");
        ApiCallback.setWFTWapPayCallback(mWFTWapPayCallback);
        WFTOrderInfoProcess wftProcess = new WFTOrderInfoProcess();
        wftProcess.setGoodsName(ApiCallback.order().getProductName());
        wftProcess.setGoodsPrice(ApiCallback.order().getGoodsPriceYuan());
        wftProcess.setGoodsDesc(ApiCallback.order().getProductDesc());
        wftProcess.setExtend(ApiCallback.order().getExtendInfo());
        wftProcess.setPayType("1");
        wftProcess.setCouponId(couponID);
        wftProcess.setRoleName(ApiCallback.order().getRoleName());
        wftProcess.setRoleId(ApiCallback.order().getRoleId());
        wftProcess.setRoleLevel(ApiCallback.order().getRoleLevel());
        wftProcess.setServerName(ApiCallback.order().getServerName());
        wftProcess.setServerId(ApiCallback.order().getGameServerId());
        wftProcess.setGoodsReserve(ApiCallback.order().getGoodsReserve());
        wftProcess.setExtra_param(ApiCallback.order().getExtra_param());
        wftProcess.post(cpHandler);
    }

    private final WFTWapPayCallback mWFTWapPayCallback = new WFTWapPayCallback() {
        @Override
        public void onResult(String code) {
            GWLog.e(TAG, "fun # wftPayCallback code = " + code);
            sendPayResult(code, "WFT");
        }
    };


    // 获取平台币信息提示框
    GWTipDialog mcTipDialog;
    /**
     * 打开提示信息
     */
    private void showDialog(String message) {
        mcTipDialog = new GWTipDialog.Builder().setMessage(message).show(this, getFragmentManager());
    }
    private void dismisDialog() {
        if (null != mcTipDialog) {
            mcTipDialog.dismiss();
        }
    }

    private void show(String message) {
        ToastUtil.show(this, message);
    }

    // TODO 支付宝-------------start
    private void zfbPayProcess() {
        ApiCallback.setZFBWapPayCallback(mZFBWapPayCallback);

        ZfbPay zfbPay = new ZfbPay(this, isZFBWapPay);
        if (isZFBWapPay){
            showDialog("给支付宝下单...");
            zfbPay.zfbPayWapProcess(cpHandler, couponID);
        }else {
            zfbPay.zfbPayProcess(couponID);
        }
    }

    private final ZFBWapPayCallback mZFBWapPayCallback = new ZFBWapPayCallback() {
        @Override
        public void onResult(String code) {
            GWLog.e(TAG, "fun # zfbPayCallback code = " + code);
            sendPayResult(code, "zfb");
        }
    };

    /**
     * 发送支付结果
     */
    protected void sendPayResult(String payResultCode, String payType) {
        GWPayModel.Instance().getPck(payResultCode, payType).callback(payResultCode);
        finish();
    }


    public Handler cpHandler = new Handler(Looper.getMainLooper()) {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            dismisDialog();
            switch (msg.what) {
                case Constant.WFT_ORDERINFO_SUCCESS:
                    WXOrderInfo wxOrderInfo = (WXOrderInfo) msg.obj;
                    Intent intent = new Intent(GWPayActivity.this, GWWapPayActivity.class);
                    intent.putExtra("WapPayOrderInfo", wxOrderInfo);
                    startActivity(intent);
                    break;
                case Constant.WFT_ORDERINFO_FAIL:
                case Constant.ZFB_WAPPAY_ORDERINFO_FAIL:
                    show("支付失败：" + msg.obj);
                    FlagControl.flag = true;
                    break;
                case Constant.ZFB_WAPPAY_ORDERINFO_SUCCESS:
                    WXOrderInfo zfbwapPayOrderInfo = (WXOrderInfo) msg.obj;
                    Intent zfbWapPayintent = new Intent(GWPayActivity.this, GWWapPayActivity.class);
                    zfbWapPayintent.putExtra("WapPayOrderInfo", zfbwapPayOrderInfo);
                    startActivity(zfbWapPayintent);
                    break;
                case Constant.PTB_MONEY_SUCCESS:  //查询平台币余额信息
                    handlerPtbInfo(msg.obj);
                    break;
                case Constant.PTB_MONEY_FAIL:
                    show("获取平台币出现异常：" + msg.obj);
                    FlagControl.flag = true;
                    break;
                case Constant.BIND_PTB_MONEY_SUCCESS:  //查询绑币余额信息
                    handlerBindPtbInfo(msg.obj);
                    break;
                case Constant.BIND_PTB_MONEY_FAIL:
                    show("获取绑余额信息出现异常：" + msg.obj);
                    FlagControl.flag = true;
                    break;
                case Constant.PTB_PAY_SUCCESS:// 平台币支付
                    handlerPTBPayResult(msg.obj);
                    break;
                case Constant.PTB_PAY_FAIL:
                    show("支付失败："+ msg.obj);
                    break;
                default:
                    break;

            }
        }
    };

    protected void handlerPTBPayResult(Object obj) {
        PTBPayResult ptbPayResult = (PTBPayResult) obj;
        dismisDialog();
        if (null != ptbPayResult && ptbPayResult.getReturn_status().equals("1")) {
            new PTBPayResultDialog.Builder()
                    .setMoney(realPrice)
                    .setGoodsName(ApiCallback.order().getProductName())
                    .setTradeWay( !isBind ? "平台币" : "余额")
                    .setTradeNo(ptbPayResult.getOrderNumber())
                    .setDialogKeyListener(backKeyListener).
                    setCloseClick(closeClick)
                    .show(this, getFragmentManager());
        } else {
            String tipStr = "支付失败";
            if (null != ptbPayResult && !TextUtils.isEmpty(ptbPayResult.getReturn_msg())) {
                tipStr = ptbPayResult.getReturn_msg();
            }
            show(tipStr);
            sendPayResult("-1", "ptb");
        }
    }

    /**
     * 返回按钮监听
     */
    DialogInterface.OnKeyListener backKeyListener = new DialogInterface.OnKeyListener() {

        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            sendPayResult("0", "ptb");
            return false;
        }
    };

    private final View.OnClickListener closeClick = new OnMultiClickListener() {
        @Override
        public void onMultiClick(View v) {
            sendPayResult("0", "ptb");
        }
    };

    private void handlerPtbInfo(Object obj) {
        FlagControl.flag = true;
        UserPTBInfo userPtb = (UserPTBInfo) obj;
        userPtbMoney = String.format(Locale.CHINA, "%.2f", userPtb.getPtbMoney());
        userBindPtbMoney = String.format(Locale.CHINA, "%.2f", userPtb.getBindptbMoney());

        float price = Float.parseFloat(realPrice);
        float ptb = GWMoneyUtils.priceToFloat(userPtbMoney);
        if ((ptb - price) >= 0) {
            ptb_pay("1");
        } else {
            show("余额不足");
        }
    }

    private void handlerBindPtbInfo(Object obj) {
        FlagControl.flag = true;
        UserPTBInfo userPtb = (UserPTBInfo) obj;
        userPtbMoney = String.format(Locale.CHINA, "%.2f", userPtb.getPtbMoney());
        userBindPtbMoney = String.format(Locale.CHINA, "%.2f", userPtb.getBindptbMoney());
        float price = Float.parseFloat(realPrice);
        float bindptbMoney = GWMoneyUtils.priceToFloat(userBindPtbMoney);
        GWLog.w(TAG, "fun#price:" + price + ", bindptbMoney:" + bindptbMoney);
        if ((bindptbMoney - price) >= 0) {
            ptb_pay("2");
        } else {
            show("平台币不足");
        }
    }

    // TODO 平台币支付请求------------------start
    public final void ptb_pay(String payType) {  //1平台币 2绑币
        showDialog("正在交易...");
        PTBPayProcess ptbpayProcess = new PTBPayProcess();
        ptbpayProcess.setGoodsName(ApiCallback.order().getProductName());
        ptbpayProcess.setGoodsPrice(ApiCallback.order().getGoodsPriceYuan());
        ptbpayProcess.setGoodsDesc(ApiCallback.order().getProductDesc());
        ptbpayProcess.setExtend(ApiCallback.order().getExtendInfo());
        ptbpayProcess.setRoleName(ApiCallback.order().getRoleName());
        ptbpayProcess.setServerName(ApiCallback.order().getServerName());
        ptbpayProcess.setRoleId(ApiCallback.order().getRoleId());
        ptbpayProcess.setServerId(ApiCallback.order().getGameServerId());
        ptbpayProcess.setExtra_param(ApiCallback.order().getExtra_param());
        ptbpayProcess.setRoleLevel(ApiCallback.order().getRoleLevel());
        ptbpayProcess.setGoodsReserve(ApiCallback.order().getGoodsReserve());
        ptbpayProcess.setCouponId(couponID);
        ptbpayProcess.setCode(payType);
        ptbpayProcess.post(cpHandler, this);
    }
}
